/**
 * Copyright [2019] [LiBo/Alex of copyright liboware@gmail.com ]
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hyts.grpc.client;

import com.hyts.grpc.base.client.AbstractGrpcClient;
import com.hyts.grpc.base.client.GrpcClient;
import com.hyts.grpc.config.GrpcConfiguration;
import com.hyts.grpc.domain.GrpcConnecion;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.stub.AbstractStub;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * @project-name:coffice-toolbox
 * @package-name:com.hyts.grpc.client
 * @author:LiBo/Alex
 * @create-date:2019-07-19 16:26
 * @copyright:libo-alex4java
 * @email:liboware@gmail.com
 * @description:
 */
@Slf4j
public class SimpleGrpcClient extends AbstractGrpcClient {

    /**
     *
     * @param subList
     */
    public SimpleGrpcClient(List<AbstractStub> subList) {
        super(subList);
    }
    /**
     * 构建客户端
     * @param param
     * @return
     */
    @Override
    public boolean build(GrpcConnecion param) {
        Objects.requireNonNull(param,"传入的连接池对象不允许为空!");
        try {
            channel = ManagedChannelBuilder.forAddress(
                    Optional.ofNullable(param.getIp()).orElse(GrpcConfiguration.DEFAULT_SERVER_ADDRESS),
                    Optional.ofNullable(param.getPort()).orElse(GrpcConfiguration.DEFAULT_SERVER_PORT)
            ).usePlaintext().build();
        } catch (Exception e) {
            log.error("构建会话对象失败!",e);
            return false;
        }
        return true;
    }


    @Override
    public boolean stop() {
        try {
            Optional.ofNullable(channel).ifPresent(ManagedChannel::shutdown);
        } catch (Exception e) {
            log.error("关闭会话对象失败!",e);
            return false;
        }
        return true;
    }
}
